# -*- coding: utf-8 -*-
'''
#----------------------------------------------------------------------------------------
# 功能：更新策划数据到内网服务器
#----------------------------------------------------------------------------------------
'''

import stat
import shutil
from flib.utils import *
from flib.SVN import SVN

if getenv("SEVEN_WORKSPACE",None):
    data_path = getenv("SEVEN_WORKSPACE") + "/" + getenv("SVN_BRANCH") + "/seven_data"
    tool_path = getenv("SEVEN_WORKSPACE") + "/" + getenv("SVN_BRANCH") + "/PC/ElementUnityWin/Tools"
else:
    data_path = "E:/Work-Space/SevenProgram/seven_data"
    tool_path = "F:/Seven/ElementUnityWin/Tools"
data_host = SVN.get_svn_host(data_path)
if not data_host: sys.exit(1)

def svn_op(*args,**kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute("svn " + param.format(**kwargs))
def svn_ci(*args):
    filelist = ""
    for x in args: filelist += '''"{file}" '''.format(file=x)
    svn_op('''add --force {filelist}''', filelist=filelist)
    svn_op('''ci -m "{log}" {filelist}''', filelist=filelist, log="jenkins export,by:" + getenv("BUILD_USER", ""))

def export_elementdata(*args,**kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute(data_path+"/eledataconsole.exe " + param.format(**kwargs))

def export_skilldata(*args,**kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute(data_path+"/eleskillconsole.exe " + param.format(**kwargs))

def export_taskdata(*args,**kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute(data_path+"/TaskExporter.exe " + param.format(**kwargs))

def export_new_template(*args, **kwargs):
    param = " ".join([str(x) for x in args])
    return safe_execute(data_path + "/TemplateEditor.exe " + param.format(**kwargs))

def equal_str(a,b):
    return toUTF8(a) == toUTF8(b)
##########################################################################################
ZLPrint("========================更新版本库==========================")
svn_op('''cleanup "{data_path}"''',data_path=data_path)
svn_op('''update "{data_path}"''',data_path=data_path)

config_url=data_host + "/DesData/Client/ClientConfig"

old_version = SVN.get_latest_version(config_url)
ZLPrint("当前版本：", old_version)
choices = toUTF8(getenv("CHOICE")).split(",")

if toUTF8("模板数据") in choices:
    ZLPrint("==============开始导出elements.data和path.data==============")

    os.chdir(data_path)
    export_elementdata('''-server_path {ser_path} -export_path {exp_path}''',ser_path=data_host,
                       exp_path=data_path+"/DesData/Client/ClientConfig/data")

    shutil.copyfile(data_path+"/DesData/Client/ClientConfig/data/elements.data", data_path+"/DesData/Server/server/elements.data")
    shutil.copyfile(data_path+"/DesData/Client/ClientConfig/data/path.data", data_path+"/DesData/Server/server/path.data")
    shutil.copyfile(data_path+"/DesData/Client/ClientConfig/data/text.data", data_path+"/DesData/Server/server/text.data")
    ZLPrint("==============结束导出elements.data和path.data==============")

    ZLPrint("========================提交版本库==========================")
    svn_ci(data_path+"/DesData/Server/server/elements.data",
        data_path+"/DesData/Server/server/path.data",
        data_path+"/DesData/Server/server/text.data",
        data_path+"/DesData/Client/ClientConfig/data/elements.data",
        data_path+"/DesData/Client/ClientConfig/data/path.data",
        data_path+"/DesData/Client/ClientConfig/data/text.data")

if toUTF8("技能数据") in choices:
    ZLPrint("======================开始导出技能数据=====================")

    os.chdir(data_path)
    export_skilldata('''{exp_path}''', exp_path=data_path+"/DesData/Client/ClientConfig/data")

    shutil.copyfile(data_path+"/DesData/Client/ClientConfig/data/skill_expression.data", data_path+"/DesData/Server/server/skill_expression.data")
    shutil.copyfile(data_path+"/DesData/Client/ClientConfig/data/skill_text.data", data_path+"/DesData/Server/server/skill_text.data")
    shutil.copyfile(data_path+"/DesData/Client/ClientConfig/data/skills.data", data_path+"/DesData/Server/server/skills.data")
    ZLPrint("======================结束导出技能数据=====================")

    ZLPrint("========================提交版本库==========================")
    svn_ci(data_path+"/DesData/Server/server/skill_expression.data",
        data_path+"/DesData/Server/server/skill_text.data",
        data_path+"/DesData/Server/server/skills.data",
        data_path+"/DesData/Client/ClientConfig/data/skill_expression.data",
        data_path+"/DesData/Client/ClientConfig/data/skill_text.data",
        data_path+"/DesData/Client/ClientConfig/data/skills.data")

if toUTF8("任务数据") in choices:
    ZLPrint("======================开始导出任务数据=====================")

    os.chdir(data_path)
    export_taskdata('''{exp_path} 1''', exp_path=data_path+"/DesData/Client/ClientConfig/data")
    import glob
    files = glob.glob(data_path+"/DesData/Client/ClientConfig/data/tasks.*")
    filelist = list()
    for x in files:
        (dirpath,filename) = os.path.split(x)
        if os.path.exists(data_path+"/DesData/Server/" + filename):
            os.chmod(data_path+"/DesData/Server/" + filename, stat.S_IWRITE)
        shutil.copyfile(x, data_path+"/DesData/Server/" + filename)
        filelist.append(x)
        filelist.append(data_path+"/DesData/Server/" + filename)
    ZLPrint("======================结束导出任务数据=====================")

    ZLPrint("========================提交版本库==========================")
    svn_ci(*filelist)

if toUTF8("新模板") in choices:
    ZLPrint("======================开始导出新模板数据=====================")

    os.chdir(data_path)
    export_new_template("--console")
    import glob
    files = glob.glob(data_path+"/DesData/Client/ClientConfig/Configs/configuration/*.*")
    files2 = glob.glob(data_path + "/DesData/Server/configuration/*.*")
    ZLPrint("======================结束导出新模板数据=====================")

    ZLPrint("========================提交版本库==========================")
    svn_ci(*files)
    svn_ci(*files2)

new_version = SVN.get_latest_version(config_url)
ZLPrint("当前版本：", new_version)
if getenv("SVN_BRANCH", "trunk") != "trunk": sys.exit(0)
if new_version > old_version:
    ZLPrint("导出差异文件列表", "{vb}：{ve}".format(vb=old_version, ve=new_version))
    local_dir = os.getcwd() + "/local_diff"
    result = SVN.export_diffs(config_url,local_dir,old_version,new_version)
    if result is None:
        ZLPrint("svn diff export failed.")
        sys.exit(1)
    ZLPrint("上传更新到服务器")
    try:
        safe_execute(
            cmds='''sh {tools_path}/make-client/resource-update.sh "../elementpacktool/ElementPackTool-pc.exe" {update_url} "{local_dir}"'''.format(
                tools_path=tool_path,
                update_url="http://10.236.100.38/seven_xevs/pc",
                local_dir=local_dir.replace('\\', '/')), logout=True)
    except Exception as e:
        raise  e
    finally:
        exec_sh(cmds='''rm -rf "{local_dir}"'''.format(local_dir=local_dir))
    sys.exit(0)
else:
    ZLPrint("没有资源变化，不用发布更新")
    sys.exit(0)


